#include <iostream>
#include "Common.hpp"
#include "InitAddr.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <unistd.h>

int main(int argv, char* argc[])
{
    if(argv != 3)
    {
        std::cout << "Usage: port ip" << std::endl;
        exit(USAGE_ERR);
    }
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cout << "socket fail" << std::endl;
        exit(SOCKET_ERR);
    }

    struct sockaddr_in local;
    std::string ip = argc[1];
    uint16_t port = std::stoi(argc[2]);

    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    inet_pton(AF_INET, ip.c_str(), &local.sin_addr);

    //客户端也要绑定，但是不需要显示绑定；客户端会在connect成功之后进行自动绑定
    InitAddr addr(port, ip);
    int m = connect(sockfd, addr.NetAddrPtr(), addr.NetAddrLen());
    if(m < 0)
    {
        std::cout << "connect fail" << std::endl;
        exit(CONNECT_ERR);
    }
    std::cout << "connect success" << std::endl;

    //3. echo clinet
    while(1)
    {
        std::string message;
        std::cout << "Please Enter@ ";
        std::getline(std::cin, message);

        int m = write(sockfd, message.c_str(), message.size());

        char buffer[1024];
        int n = read(sockfd, buffer, sizeof(buffer) - 1);
        buffer[n] = 0;
        std::cout << "Server echo@ " << message << std::endl;
    }
    return 0;
}